package tech.summerly.weather.data.local

import tech.summerly.weather.data.bean.Forecast
import tech.summerly.weather.data.bean.RealTime
import tech.summerly.weather.model.Region

/**
 * 为天气提供一个缓存
 */
object WeatherCache {

    private const val LIMIT = 1000 * 60 * 60

    private val realtimePersistence = SimplePersistence(name = "realtime_pref")

    private val forecastPersistence = SimplePersistence(name = "forecast_pref")

    /**
     * 获取缓存中的实时天气信息
     */
    suspend fun getRealtimeWeather(region: Region): RealTime? {
        return realtimePersistence.get<Cache<RealTime>>(region.fullName)?.get()
    }

    /**
     * 获取缓存中的天气预报信息
     */
    suspend fun getForecastWeather(region: Region): Forecast? {
        val cache = forecastPersistence.get<Cache<Forecast>>(region.fullName) ?: return null
        return cache.get()
    }

    /**
     * 刷新缓存中的实时天气信息
     */
    fun refreshRealtimeWeather(region: Region, realTime: RealTime) {
        realtimePersistence[region.fullName] = Cache(System.currentTimeMillis(), realTime)
    }

    /**
     * 刷新缓存中的天气预报信息
     */
    fun refreshWeatherForecast(region: Region, forecast: Forecast) {
        forecastPersistence[region.fullName] = Cache(System.currentTimeMillis(), forecast)
    }


    class Cache<out T>(
            val timestamp: Long,
            val value: T
    ) {
        fun get(): T? {
            if (timestamp < System.currentTimeMillis() - LIMIT) {
                return null
            }
            return value
        }
    }
}